package net.happy2v.file.server.test.file.handler;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import net.ib.mn.protocol.CommonEnvelope.Envelope;
import net.ib.mn.protocol.File.EFMethodId;
import net.ib.mn.protocol.File.FileCategory;
import net.ib.mn.protocol.File.FileKey;
import net.ib.mn.protocol.File.UploadReq;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.google.protobuf.ByteString;


public class FileUploadHanlder extends SimpleChannelUpstreamHandler{

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		System.out.println("messageReceived FileUploadHandler");
		if (!(e.getMessage() instanceof Envelope)) {
            return;
        }
		
		Envelope enveolope = (Envelope) e.getMessage();
		
		if(enveolope.getMethodId() == EFMethodId.METHOD_EF_File_Upload.getNumber()){
			UploadReq req = UploadReq.parseFrom(enveolope.getBody());
			System.out.println("SliceNo : " + req.getSliceNo());
			System.out.println("SliceSize : " + req.getDataSize());
			
			FileKey fileKey = req.getFileKey();
			FileCategory fileCategory = fileKey.getFileCategory();
			System.out.println("FileCategory : " + fileCategory);
			System.out.println("File Name : " + fileKey.getFileName());
			System.out.println("File Type : " + fileKey.getFileType());
			System.out.println("File UUID : " + fileKey.getFileUuid());
			
			ByteString byteString = req.getFileData();
			byte[] byteBuffer = byteString.toByteArray();
			File file = new File("./file/test3.jpg");
			
			file.delete();
			file.createNewFile();
			
			FileOutputStream fos = new FileOutputStream(file);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			bos.write(byteBuffer, 0, byteBuffer.length);
			bos.flush();
			bos.close();
			fos.close();
			
			System.out.println("@@@@  FILE WRITE END    @@@@@@");
			System.out.print("\n\r");
			
			System.out.println("file length() : " + file.length());
		}
		super.messageReceived(ctx, e);
	}
}
